// store/cart.js
export default {
  state: {
    cartItems: [], // 购物车商品列表
  },
  mutations: {
    // 添加商品到购物车
    addToCart(state, product) {
      const existingItem = state.cartItems.find(item => item.goodsId === product.goodsId)
      console.log('existingItem', existingItem)
      if (existingItem) {
        existingItem.goodsCount = product.goodsCount
      } else {
        state.cartItems.push({
          ...product,
          // goodsCount: 1,
          selected: true,
        })
      }
      console.log(' state.cartItems', state.cartItems)
      uni.setStorageSync('cart', state.cartItems) // 同步到本地存储
    },

    // 更新商品数量
    updateGoodsCount(state, { goodsId, goodsCount }) {
      console.log('updateGoodsCount', goodsId)
      const item = state.cartItems.find(item => item.goodsId === goodsId)
      if (item) {
        item.goodsCount = goodsCount
        uni.setStorageSync('cart', state.cartItems)
      }
    },

    // 从购物车移除商品
    removeFromCart(state, goodsId) {
      console.log('removeFromCart', goodsId)
      state.cartItems = state.cartItems.filter(item => item.goodsId !== goodsId)
      uni.setStorageSync('cart', state.cartItems)
    },

    // 初始化购物车
    initCart(state) {
      const cart = uni.getStorageSync('cart') || []
      state.cartItems = cart
    },
    // 清空购物车
    clearCart(state) {
      console.log('clearCart')
      state.cartItems = []
      uni.removeStorageSync('cart')
    },
    // 清空购物车选中的商品
    clearCartSelected(state) {
      console.log('clearCartSelected')
      state.cartItems = state.cartItems.filter(item => !item.selected)
      uni.setStorageSync('cart', state.cartItems)
    },
    // 更新购物车是否选中
    toggleSelect(state, goodsId) {
      const item = state.cartItems.find(item => item.goodsId === goodsId)
      if (item) {
        item.selected = !item.selected
        uni.setStorageSync('cart', state.cartItems)
      }
    },
    // 更新购物车是否选中
    triggerSelectAll(state, status) {
      console.log('status', status)
      state.cartItems.forEach(item => {
        item.selected = status
      })
      uni.setStorageSync('cart', state.cartItems)
    },
  },

  getters: {
    // 计算总数量
    totalGoodsCount: state => {
      return state.cartItems.reduce((total, item) => total + item.goodsCount, 0)
    },
    // 计算总价格
    totalPrice: state => {
      const list = state.cartItems.filter(item => item.selected)
      const totalPrice = list.reduce((total, item) => total + Number(item.taxPrice * item.goodsCount), 0)
      return totalPrice.toFixed(2)
    },
    totalNum: state => {
      return state.cartItems.length
    },
  },
}
